﻿Imports System.Data
Imports System.Web


Public Class offline_edit

    Dim open_cnt As Integer = 0
    Dim table As DataTable
    Dim currentColumnString As String
    Dim isEscapeEncoded As Boolean = False
    Dim openFile As String
    'Dim ds As DataSet


    Private Sub OpenToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripButton.Click


        If open_cnt >= 1 Then
            main.reloadOffline()
            ' MessageBox.Show("Please close program and start again. Sorry, will fix this later")
            Exit Sub
        End If
        Dim LoadedXML As New xml_loader()
        LoadedXML.loadTable()

        If LoadedXML.IS_LOADED Then 'if user cancelled load - then need to exit sub (empty table is returned causing array overflow
            table = LoadedXML.GET_TABLE
            open_cnt += 1
        Else
            Exit Sub
        End If



        DataGridView1.DataSource = LoadedXML.GET_TABLE ' specified this in the properties pane using GUI navigator
        BindingSource1.DataSource = table

        create_Form() 'create the dynamic text boxes

        populate_ToolStripComboBoxColumnSelector()
        Me.Text = Me.Text & " - " & LoadedXML.GET_FILENAME
        openFile = LoadedXML.GET_FILENAME

    End Sub

    Private Sub populate_ToolStripComboBoxColumnSelector()


        Dim x As Integer
        Do Until x = DataGridView1.ColumnCount
            ToolStripComboColumnSelector.Items.Add(DataGridView1.Columns(x).Name)
            x += 1
        Loop
        ToolStripComboColumnSelector.SelectedIndex = 0

    End Sub
    Public Sub create_Form()
        ' Working version of Dynamic Label and textbox creator for Dynamic Data
        Dim label As Label
        Dim textBox As TextBox
        Dim yPos As Integer = 30
        Dim I As Integer
        For I = 0 To table.Columns.Count - 1
            label = New Label()
            label.Location = New Point(0, yPos)
            label.AutoSize = True
            label.Text = table.Columns(I).ColumnName + ":"
            'Controls.Add(label)
            Panel1.Controls.Add(label)
            textBox = New TextBox
            textBox.Location = New Point(90, yPos)
            textBox.Width = 200
            textBox.DataBindings.Add("Text", BindingSource1, table.Columns(I).ColumnName)
            'Controls.Add(textBox)
            Panel1.Controls.Add(textBox)

            yPos += 30
        Next
        ''place trhe rich text box in a sensible place
        label = New Label()
        label.Location = New Point(0, yPos)
        label.AutoSize = True
        label.Text = "HTML Parser:"
        Panel1.Controls.Add(label)
        'textBox = New TextBox
        RichTextBox1.Location = New Point(90, yPos)
        RichTextBox1.Width = 200
        RichTextBox1.Height = 150
        'Panel1.Controls.Add(RichTextBox1)
        RichTextBox1.DataBindings.Clear()
        Try
            RichTextBox1.DataBindings.Add("Text", BindingSource1, "Description")
        Catch ex As Exception

        End Try



        'DataGridView1.CurrentCell = DataGridView1.Rows(Convert.ToInt32(BindingNavigatorPositionItem.Text) - 1).Cells(0)
        'DataGridView1.Update()
        'updateSelections()
    End Sub


    Private Sub BindingNavigatorMoveNextItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BindingNavigatorMoveNextItem.Click
        Dim x As Integer
        x = Convert.ToInt32(BindingNavigatorPositionItem.Text) + 1
        DataGridView1.CurrentCell = DataGridView1.Rows(x - 1).Cells(0)
    End Sub

    Private Sub BindingNavigatorMovePreviousItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BindingNavigatorMovePreviousItem.Click
        Dim x As Integer
        x = Convert.ToInt32(BindingNavigatorPositionItem.Text) - 1
        DataGridView1.CurrentCell = DataGridView1.Rows(x - 1).Cells(0)
    End Sub



    Private Sub SaveToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveToolStripButton.Click
        table.AcceptChanges()

        Dim dv As DataView = CType(BindingSource1.List, DataView)
        Dim dt As DataTable = dv.ToTable()

        Dim xml_saver As New xml_loader
        'xml_saver.save_xml("", table, ToolStripProgressBar1) 'no filename specified-will open save file dialog -if specified then overwrite and no promtp!
        Dim btn As New Button
        xml_saver.save_xml("", dt, btn) 'no filename specified-will open save file dialog -if specified then overwrite and no promtp!

    End Sub


    Private Sub ToolStripButtonUploadAndImport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonUploadAndImport.Click
        Dim uploader As New FtpConnector
        Dim loader As New OpenFileDialog

        uploader.upload(openFile, My.Settings.ftp_site, My.Settings.ftp_import_dir, My.Settings.ftp_import_file)

        Dim profiler As New webAdmin
        'profiler.adminURL = "http://www.tecnikk.co.uk/index.php/admin/system_convert_gui/run/id/9/" 'import XML based files only!
        profiler.adminURL = My.Settings.www_site & My.Settings.www_run & My.Settings.www_id_importXML
        profiler.ShowDialog()
    End Sub

    Private Sub ToolStripButtonExportAndDownload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonExportAndDownload.Click
        Dim profiler As New webAdmin
        'profiler.adminURL = "http://www.tecnikk.co.uk/index.php/admin/system_convert_gui/run/id/8/"
        profiler.adminURL = My.Settings.www_site & My.Settings.www_run & My.Settings.www_id_exportXML

        If profiler.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Dim downloader As New FtpConnector
            Dim saveDialog As New SaveFileDialog
            'downloader.download("C:\magento\", "desc_export.xml", "desc_export.xml")
            downloader.download(My.Settings.local_workPath, "desc_export.xml", My.Settings.ftp_site, My.Settings.ftp_export_dir, My.Settings.ftp_export_file)
            'MessageBox.Show("If no errors occured you should be able to load 'desc_import.xml' now.")
        End If
    End Sub

    Private Sub offline_edit_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        My.Settings.MB_height = Me.Height
        My.Settings.MB_width = Me.Width
        My.Settings.MB_split1 = SplitContainer1.SplitterDistance
        My.Settings.MB_split2 = SplitContainer2.SplitterDistance
        My.Settings.MB_locX = Me.Location.X
        My.Settings.MB_locY = Me.Location.Y

        If Me.WindowState = FormWindowState.Maximized Then
            My.Settings.MB_isMaximized = True
        Else
            My.Settings.MB_isMaximized = False
        End If

        'dispose of main-no longer needed here
        main.Visible = True
        main.WindowState = FormWindowState.Normal


    End Sub


    Private Sub offline_edit_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Dim catPicker As New categoryPicker
        'catPicker.loadFile("c:\magento\categories.csv", ToolStripComboBoxCategories)
        If My.Settings.MB_isMaximized = True Then
            Me.WindowState = FormWindowState.Maximized
        Else
            Me.WindowState = FormWindowState.Normal
            Me.Location = New System.Drawing.Point(My.Settings.MB_locX, My.Settings.MB_locY)
        End If

        Me.Height = My.Settings.MB_height
        Me.Width = My.Settings.MB_width
        SplitContainer1.SplitterDistance = My.Settings.MB_split1
        SplitContainer2.SplitterDistance = My.Settings.MB_split2

        If My.Computer.FileSystem.FileExists(My.Settings.plugin_tinymce_DirThisSystem) Then
            WebBrowser1.Navigate(My.Settings.plugin_tinymce_DirThisSystem)
        Else
            WebBrowser1.Navigate("")
        End If
    End Sub

    'specific command that each change of combo box should do to datagridview current cell
    Private Sub ToolStripComboBoxCategories_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripComboBoxCategories.SelectedIndexChanged
        If ToolStripComboBoxCategories.SelectedIndex > 0 And DataGridView1.Rows.Count > 0 Then
            Select Case currentColumnString
                Case "category_ids"
                    comboBoxFunctionCATEGORYIDS()
                Case "status"
                    comboBoxFunctionSTATUS()
                Case "small_image", "thumbnail", "image"
                    comboBoxFunctionLOADFILE()
            End Select

        End If
    End Sub

    'working with the GRID check which column is current and load combobox if available
    
    Private Sub DataGridView1_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
        BindingSource1.Position = DataGridView1.CurrentCell.RowIndex
        currentColumnString = table.Columns(DataGridView1.CurrentCell.ColumnIndex).ColumnName

        Select Case currentColumnString
            Case "category_ids"
                comboBoxSelector(currentColumnString)
            Case "status"
                comboBoxSelector(currentColumnString)
            Case "small_image", "thumbnail", "image"
                comboBoxSelector(currentColumnString)
            Case Else
                ToolStripComboBoxCategories.Text = "Column not found"
                ToolStripComboBoxCategories.Enabled = False


        End Select

    End Sub

    'extra sub to place all the LOADING of combobox only - do not put gridmanipulation in here otherwise array overflow will occur!!
    Public Sub comboBoxSelector(ByVal _comboBoxType As String)
        ToolStripComboBoxCategories.Enabled = True
        ToolStripComboBoxCategories.Items.Clear()

        contextMenuForDataGrid.MenuItems.Clear()
        contextMenuForDataGridEnabled = False

        Select Case _comboBoxType
            Case "category_ids"
                ToolStripComboBoxCategories.Text = "Category ID's"
                Dim catPicker As New categoryPicker
                'catPicker.loadFile("c:\magento\categories.csv", ToolStripComboBoxCategories)
                catPicker.loadFile(My.Settings.local_workPath & "\categories.csv", ToolStripComboBoxCategories)
            Case "status"
                ToolStripComboBoxCategories.Text = "Item Status"
                ToolStripComboBoxCategories.Items.Add("Enabled")
                ToolStripComboBoxCategories.Items.Add("Disabled")
            Case "small_image", "thumbnail", "image"
                ToolStripComboBoxCategories.Text = "Right Click"
                comboBoxFunctionLOADFILE()
        End Select

    End Sub

    Dim contextMenuForDataGrid As New ContextMenu
    Dim contextMenuForDataGridEnabled As Boolean = False

    Public Sub comboBoxFunctionLOADFILE()
        contextMenuForDataGridEnabled = True
        contextMenuForDataGrid.MenuItems.Add("Choose File...", New EventHandler(AddressOf righClickHandler))
    End Sub

    Private Sub DataGridView1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseUp
        If contextMenuForDataGridEnabled And e.Button = Windows.Forms.MouseButtons.Right Then
            Dim dgv = CType(sender, DataGridView)
            '
            Dim pnt As New Point(e.X, e.Y)
            ' contextMenuForDataGrid.Show(DataGridView1, pnt) 'forgert about context menu for now jsut laod file
            righClickHandler(Nothing, Nothing)
        End If
    End Sub

    Private Sub righClickHandler(ByVal sender As Object, ByVal e As EventArgs)
        Dim fileChooser As New OpenFileDialog
        fileChooser.ShowDialog()
        DataGridView1.CurrentCell.Value = "/" & fileChooser.FileName.Remove(0, fileChooser.FileName.LastIndexOf(CChar("\")) + 1)
        DataGridView1.Focus()
    End Sub

    Public Sub comboBoxFunctionCATEGORYIDS()
        Dim tmpArray As String()
        tmpArray = ToolStripComboBoxCategories.Items.Item(ToolStripComboBoxCategories.SelectedIndex).ToString.Split(CChar(","))

        If DataGridView1.CurrentCell.Value.ToString.Equals("") Or DataGridView1.CurrentCell.Value.ToString.Equals(" ") Then
            DataGridView1.CurrentCell.Value = tmpArray(0)
        Else
            DataGridView1.CurrentCell.Value = DataGridView1.CurrentCell.Value.ToString & "," & tmpArray(0)
        End If
        DataGridView1.Focus()
    End Sub

    Public Sub comboBoxFunctionSTATUS()
        Dim tmpString As String

        tmpString = ToolStripComboBoxCategories.Items.Item(ToolStripComboBoxCategories.SelectedIndex).ToString
        DataGridView1.CurrentCell.Value = tmpString
        DataGridView1.Focus()
    End Sub

    Private Sub RichTextBox1_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.Enter
        RichTextBox1.Text = My.Computer.Clipboard.GetText
    End Sub


    Private Sub RichTextBox1_Leave1(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.Leave

        'remove all caridge return and paragraph items to avaiod extra spacing on html decode server side
        'If CheckBoxParseHTML.Checked Then

        Dim modifyRtf As String = RichTextBox1.Rtf
        Dim flatTextRTF As String = ""
        For i As Integer = 0 To 3 ' looop twice to remove RTF formatting and coding - then work with text to avoid side-effects-
            Dim x As Integer
            x = modifyRtf.IndexOf(CChar(" "))
            flatTextRTF += modifyRtf.Substring(0, x + 1)
            modifyRtf = modifyRtf.Remove(0, x + 1)
        Next

        'flatTextRTF += modifyRtf.Replace("\par", "&#xD;&#10;")'works ok but if use tables makes 10 spaaces?
        'flatTextRTF += modifyRtf.Replace("\par", "&#xD;")'works ok but if use tables makes 10 spaaces?
        'flatTextRTF += modifyRtf.Replace("\par", "&#10;")'works ok but if use tables makes 10 spaaces? whats the diff?? :(
        flatTextRTF += modifyRtf.Replace("\par", " ")
        RichTextBox1.Rtf = flatTextRTF
        'string of text with absolutely no enters ready for encoding
        '------------------- always do the above!

        RichTextBox1.Text = HttpUtility.HtmlEncode(RichTextBox1.Text) 'implicit conversion to entities'

        'DataGridView1.CurrentCell.Value = RichTextBox1.Text
    End Sub


    Private Sub ToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        My.Computer.Clipboard.SetText(HttpUtility.HtmlDecode(RichTextBox1.Text))
    End Sub

    Public Sub externalReload()
        OpenToolStripButton_Click(Me, EventArgs.Empty)

    End Sub

    Private Sub ToolStripTextBoxFilter_KeyUp1(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles ToolStripTextBoxFilter.KeyUp
        Dim selectedColumn As String

        If ToolStripComboColumnSelector.Items.Count > 0 Then
            selectedColumn = ToolStripComboColumnSelector.Items.Item(ToolStripComboColumnSelector.SelectedIndex).ToString

            BindingSource1.Filter = selectedColumn & " LIKE '" & ToolStripTextBoxFilter.Text & "%'"
        End If

    End Sub


    Private Sub ToolStripButton2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton2.Click
        Pictures.Show()
    End Sub

    Private Sub ToolStripButtonPictureUploader_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonPictureUploader.Click
        Dim pxup As New PictureUploader
        PictureUploader.Show()
    End Sub

    Private Sub ToolStripButton1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton1.Click
        'RichTextBox1.Text = HttpUtility.HtmlEncode(RichTextBox1.Text) 'implicit conversion to entities'
        My.Computer.Clipboard.SetText(HttpUtility.HtmlDecode(RichTextBox1.Text))

    End Sub
End Class